Imports System.IO
Imports System.Threading

Public Class Form1
    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim retval As Int32
        Dim readers(-1)() As Char
        Dim i As Int32
        Try

        retval = GetReaders(readers)
            If retval = SCARD_E_NO_SERVICE Then
                Status1.Text = "Smart Card service not started"
                Return
            ElseIf retval = SCARD_E_NO_READERS_AVAILABLE Then
                Status1.Text = "No readers available"
                Return
            ElseIf retval <> 0 Then
                Status1.Text = "Error listing reader"
                Return
            End If

            For i = 0 To readers.GetUpperBound(0)
                lsbReader.Items.Add(CStr(readers(i)))
            Next
            lsbReader.SelectedIndex = 0
            Status1.Text = "Ready"
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation)
        End Try

    End Sub

    Private Sub Form1_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Leave
        ReleaseContext()
    End Sub

    Private Sub btnRead_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRead.Click
        Try
            Dim t As New Thread(AddressOf ThreadProc)
            Form.CheckForIllegalCrossThreadCalls = False
            btnRead.Enabled = False
            Me.ToolStripButton2.Enabled = False
            Me.ToolStripButton3.Enabled = False
            Me.ToolStripButton1.Enabled = False
            Me.PrintToolStripMenuItem.Enabled = False
            t.Start()
            Thread.Sleep(0)
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation)
        End Try
    End Sub

    Sub ThreadProc()
        Status1.Text = "Connecting to card..."
        If SelectReader(lsbReader.SelectedItem) = False Then
            Status1.Text = "Can't connect to smart card"
            btnRead.Enabled = True
            Return
        End If
        Status1.Text = "Reading"
        CacheJPN1()
        'Dim str As String = ReadInfo("Name")
        'Dim str2 As String
        'str2 = String.Join(vbCrLf, str)
        'MessageBox.Show(String.Join(vbCrLf, str.ToString))
        txtName.Text = ReadInfo("Name").ToString.Replace(vbCrLf, " ")
        txtIC.Text = ReadInfo("IC")
        txtOldIC.Text = ReadInfo("OldIC")
        txtDOB.Text = ReadInfo("DOB")
        txtPOB.Text = ReadInfo("POB")
        txtGender.Text = ReadInfo("Gender")
        txtCitizen.Text = ReadInfo("Citizen")
        txtIssueDate.Text = ReadInfo("IssueDate")
        txtRace.Text = ReadInfo("Race")
        txtReligion.Text = ReadInfo("Religion")
        txtAddress.Text = ReadInfo("Address")
        cachedJPN1 = False

        Dim memstream As New MemoryStream
        Status1.Text = "Reading photo, takes about 7s"
        ReadPhoto(memstream)
        PictureBox1.Image = System.Drawing.Image.FromStream(memstream)
        btnRead.Enabled = True
        Me.ToolStripButton2.Enabled = True
        Me.ToolStripButton3.Enabled = True
        Me.ToolStripButton1.Enabled = True
        Me.PrintToolStripMenuItem.Enabled = True
        Status1.Text = "Ready"
    End Sub

    Private Sub cmdVerify_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

   
    Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage

        Try

        'PrintPage is the foundational printing event. This event gets fired for every
            ' page that will be printed
            Static intCurrentChar As Int32
            ' declaring a static variable to hold the position of the last printed char
            Dim font As New Font("Verdana", 14)
            ' initializing the font to be used for printing
            Dim PrintAreaHeight, PrintAreaWidth, marginLeft, marginTop As Int32
            With PrintDocument1.DefaultPageSettings
                ' initializing local variables that contain the bounds of the printing area rectangle
                PrintAreaHeight = .PaperSize.Height - .Margins.Top - .Margins.Bottom
                PrintAreaWidth = .PaperSize.Width - .Margins.Left - .Margins.Right
                ' initializing local variables to hold margin values that will serve
                ' as the X and Y coordinates for the upper left corner of the printing
                ' area rectangle.
                marginLeft = .Margins.Left
                marginTop = .Margins.Top
                ' X and Y coordinate
            End With

            If PrintDocument1.DefaultPageSettings.Landscape Then
                Dim intTemp As Int32
                intTemp = PrintAreaHeight
                PrintAreaHeight = PrintAreaWidth
                PrintAreaWidth = intTemp
                ' if the user selects landscape mode, swap the printing area height and width
            End If

            Dim pfont As Font = New Font("Arial", 12)
            Dim ppen As New Pen(Color.Black, 3)
            Dim pheight As Integer = CInt(pfont.GetHeight(e.Graphics))
            Dim xpos As Integer = CInt(e.MarginBounds.Left)
            Dim ypos As Integer = CInt(e.MarginBounds.Top)


            Dim intLineCount As Int32 = CInt(PrintAreaHeight / font.Height)
            ' calculating the total number of lines in the document based on the height of
            ' the printing area and the height of the font
            Dim rectPrintingArea As New RectangleF(marginLeft, marginTop, PrintAreaWidth, PrintAreaHeight)
            ' initializing the rectangle structure that defines the printing area
            Dim fmt As New StringFormat(StringFormatFlags.LineLimit)
            'instantiating the StringFormat class, which encapsulates text layout information
            Dim intCharsFitted As Int32

            Dim Header As String = "PERBANDANAN PUTRAJAYA"
            font = New Font("Verdana", 18, FontStyle.Bold, GraphicsUnit.Point)
            e.Graphics.DrawString(Header, font, Brushes.Black, xpos, ypos)
            ypos = ypos + CInt(font.GetHeight(e.Graphics))
            e.Graphics.DrawString("APTS & APS", pfont, Brushes.Black, xpos, ypos)
            ypos += pheight
            e.Graphics.DrawString("Printed : " & Date.Now.ToString, New Font("Arial", 10, FontStyle.Italic), Brushes.Black, xpos, ypos)
            ypos += pheight

            e.Graphics.DrawLine(ppen, xpos, ypos, e.MarginBounds.Right - 100, ypos)
            ypos += pheight

            e.Graphics.DrawString("MyKad Information", pfont, Brushes.Black, xpos, ypos)

            ypos += pheight

            'set image
            Dim img As Image = Me.PictureBox1.Image

            'image size in 1/100 inch measurement
            Dim sz As New SizeF(100 * img.Width / img.HorizontalResolution, _
                            100 * img.Height / img.VerticalResolution)
            'Dim p As New PointF((e.PageBounds.Width - sz.Width) / 2, (e.PageBounds.Height - sz.Height) / 2)
            Dim p As New PointF((e.PageBounds.Width - sz.Width) / 2, ypos)
            e.Graphics.DrawImage(img, p)
            'e.Graphics.DrawImage(Me.PictureBox1.Image, New Rectangle(0, 0, Me.PictureBox1.Width, Me.PictureBox1.Height))
            ypos = ypos + (img.Height)
            ypos += pheight
            ypos += pheight
            Dim str As String
            e.Graphics.DrawString("Name : " & Me.txtName.Text, pfont, Brushes.Black, xpos, ypos, fmt)
            ypos += pheight
            str = "IC No. : " & Me.txtIC.Text & Space(15)
            e.Graphics.DrawString(str, pfont, Brushes.Black, xpos, ypos, fmt)
            ypos += pheight
            str = "Old IC : " & Me.txtOldIC.Text
            e.Graphics.DrawString(str, pfont, Brushes.Black, xpos, ypos, fmt)
            ypos += pheight

            str = "Date of Birth : " & Me.txtDOB.Text
            e.Graphics.DrawString(str, pfont, Brushes.Black, xpos, ypos, fmt)
            ypos += pheight
            str = "Gender : " & Me.txtGender.Text
            e.Graphics.DrawString(str, pfont, Brushes.Black, xpos, ypos, fmt)
            ypos += pheight

            str = "Place of Birth : " & Me.txtPOB.Text
            e.Graphics.DrawString(str, pfont, Brushes.Black, xpos, ypos, fmt)
            ypos += pheight
            str = "Citizenship : " & Me.txtCitizen.Text
            e.Graphics.DrawString(str, pfont, Brushes.Black, xpos, ypos, fmt)
            ypos += pheight
            str = "Race : " & Me.txtRace.Text
            e.Graphics.DrawString(str, pfont, Brushes.Black, xpos, ypos, fmt)
            ypos += pheight
            str = "Issued Date : " & Me.txtIssueDate.Text
            e.Graphics.DrawString(str, pfont, Brushes.Black, xpos, ypos, fmt)
            ypos += pheight

            str = "Religion : " & Me.txtReligion.Text
            e.Graphics.DrawString(str, pfont, Brushes.Black, xpos, ypos, fmt)
            ypos += pheight
            e.Graphics.DrawString("Address :", pfont, Brushes.Black, xpos, ypos, fmt)
            ypos += pheight
            str = Me.txtAddress.Text
            e.Graphics.DrawString(str, pfont, Brushes.Black, xpos, ypos, fmt)
            ypos += pheight * 7
            e.Graphics.DrawLine(ppen, xpos, ypos, e.MarginBounds.Right - 100, ypos)
            ypos += pheight
            e.Graphics.DrawString("Comments ", pfont, Brushes.Black, xpos, ypos, fmt)
            ypos += pheight * 4
            e.Graphics.DrawLine(ppen, xpos, ypos, e.MarginBounds.Right - 100, ypos)
            ypos += pheight * 5
            e.Graphics.DrawString("--------------------------" & Space(50) & "---------------------------", pfont, Brushes.Black, xpos, ypos, fmt)
            ypos += pheight
            e.Graphics.DrawString("Signature Owner  " & Space(60) & "Officer", pfont, Brushes.Black, xpos, ypos, fmt)
            'e.Graphics.MeasureString(Mid(RichTextBox1.Text, intCurrentChar + 1), font, New SizeF(PrintAreaWidth, PrintAreaHeight), fmt, intCharsFitted, intLinesFilled)
            ' calling MeasureString to determine the number of characters that will fit in
            ' the printing area rectangle
            'e.Graphics.DrawString(" Name : " & Mid(RichTextBox1.Text, intCurrentChar + 1), font, Brushes.Black, rectPrintingArea, fmt)
            ' print the text to the page
            intCurrentChar += intCharsFitted
            'advancing the current char to the last char printed on this page
            '      If TextBox1.Text.Length Then
            'If intCurrentChar e.HasMorePages=True
            'HasMorePages tells the printing module whether another PrintPage event should be fired
            'Else
            e.HasMorePages = False
            intCurrentChar = 0
            'End If

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

    End Sub

    Private Sub ReadToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ReadToolStripMenuItem.Click
        Me.btnRead.PerformClick()
    End Sub

    Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        If MessageBox.Show(Me, "Are you sure to exit?", Me.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then

            Application.Exit()
        End If

    End Sub

    Private Sub ToolStripButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton1.Click
        Me.btnRead.PerformClick()
    End Sub

    Private Sub ToolStripButton2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton2.Click
        If PrintDialog1.ShowDialog = DialogResult.OK Then
            'showDialog method makes the dialog box visible at run time
            PrintDocument1.Print()
        End If

    End Sub

    Private Sub PrintToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PrintToolStripMenuItem.Click
        If PrintDialog1.ShowDialog = DialogResult.OK Then
            'showDialog method makes the dialog box visible at run time
            PrintDocument1.Print()
        End If

    End Sub
    Sub clearfield()
        Try

        txtName.Text = ""
            txtIC.Text = ""
            txtOldIC.Text = ""
            txtDOB.Text = ""
            txtPOB.Text = ""
            txtGender.Text = ""
            txtCitizen.Text = ""
            txtIssueDate.Text = ""
            txtRace.Text = ""
            txtReligion.Text = ""
            txtAddress.Text = ""
            'Dim memstream As New MemoryStream
            'Dim img As Image
            PictureBox1.Image = Me.PictureBox2.Image     '.FromStream(memstream)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try

    End Sub

    Private Sub ToolStripButton3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton3.Click
        clearfield()
    End Sub

    Private Sub txtIC_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtIC.TextChanged

    End Sub

    Private Sub txtName_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtName.TextChanged

    End Sub

    Private Sub AboutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AboutToolStripMenuItem.Click
        Dim f As New AboutBox1
        f.Show(Me)
    End Sub

    Private Sub ToolStripButton4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton4.Click
        ExitToolStripMenuItem.PerformClick()
    End Sub
End Class
